<?php
/**
 * 登录相关业务
 */

namespace app\api\business;
use app\common\lib\Str;
use app\common\lib\Time;
use think\Exception;
use app\common\model\redis\RedisModel;
use think\facade\Db;
class LoginBus extends BaseBus
{

    /**
     * 登录验证业务
     * @param $data // 用户登录提交数据
     * @return bool
     * @throws Exception
     */
    public static function login($data)
    {
        try{
            $userInfo = \app\api\business\UserInfoBus::getUserByUserNumber($data['number']);
            if(empty($userInfo)){
                return returnResultExit(config("config.code.error"),'用户不存在!');
            }
            //判断密码是否正确
            if($userInfo['password'] != md5($data['password'])){
                return returnResultExit(config("config.code.error"),'密码错误!');
            }
            // 记录session数据
            session('users',$userInfo);
            //验证token
            $RedisModel = new RedisModel();
            $token_id = $RedisModel->getValue(config("redis.token_id").$userInfo['id']);
            $token_pre = $RedisModel->getValue(config("redis.token_pre").$token_id);
            $redisData = [ "id" => $userInfo['id'], "number" => $userInfo['number']];
            $redisData = json_encode($redisData);
            if(!$token_pre){
                // 获取token
                $token  = Str::getLoginToken($userInfo['number']);
                // 以用户ID保存用户的唯一token
                $RedisModel->setexValue(config("redis.token_id").$userInfo['id'],$token,Time::userLoginExpiresTime());
                // 保存用户token的相关数据
                $RedisModel->setexValue(config("redis.token_pre").$token,$redisData,Time::userLoginExpiresTime());
            }else{
                $token = $RedisModel->getValue(config("redis.token_id").$userInfo['id']);
                // 以用户ID保存用户的唯一token
                $RedisModel->setexValue(config("redis.token_id").$userInfo['id'],$token,Time::userLoginExpiresTime());
                // 保存用户token的相关数据
                $RedisModel->setexValue(config("redis.token_pre").$token,$redisData,Time::userLoginExpiresTime());
            }
            $q = Db::table('menu')->select();
            $list = [];
            foreach ($q as $index =>$value) {
                if($value['levels']==0){
                    if(empty($value['url'])){
                        $value['url'] = '/';
                    }
                    $q=[
                        'path'=>"/",
                        'component'=>'Layout',
                        'redirect'=>'/'.$value['url'],
                        'children'=>[[
                            'path'=>$value['url'],
                            'component'=>$value['url'],
                            'name'=>$value['url'],
                            'meta'=>['title'=>$value['title'], 'icon'=>'size']
                        ]]
                    ];
                    $list[$value['id']]=$q;
                }else{
                    $s = [
                        'path'=>"/",
                        'component'=>'Layout',
                        'name'=>$value['url'],
                        'meta'=>['title'=>$value['title'], 'icon'=>'size']
                    ];
                    array_push($list[$value['levels']]['children'],$s);
                }
            }
//            array_push($list,['path'=>'*','redirect'=>'/404', 'hidden'=> true]);
            return $token ? ["token"=>$token,"number"=>$userInfo['number'],'roles'=>array_merge($list)]: false;
        } catch(\Exception $e) {
            exception($e,'login');
        }
    }

    /**
     * 更新token时间
     * @param $token
     * @return bool
     * @throws Exception
     */
    public static function heartbeat($token){
        try{
            $RedisModel = new RedisModel();
            $token_pre = $RedisModel->getValue(config("redis.token_pre").$token);
            if($token_pre){
                $userInfo = json_decode($token_pre,true);
                $RedisModel->setexValue(config("redis.token_id").$userInfo['id'],$token,Time::userLoginExpiresTime());
                $RedisModel->setexValue(config("redis.token_pre").$token,$token_pre,Time::userLoginExpiresTime());
                return true;
            }
            return false;
        } catch(\Exception $e) {
            exception($e,'heartbeat');
        }
    }

}
